import re
import chardet
import pandas as pd
import tkinter as tk
from tkinter import filedialog

def detect_encoding(file_path):
    """检测文件编码"""
    with open(file_path, 'rb') as file:
        result = chardet.detect(file.read())
    return result['encoding']





def extract_nmap_targets(file_path):
    """从文件中提取Nmap扫描目标和MAC地址信息"""
    target_pattern = r'Nmap scan report for (\S+)'
    mac_address_pattern = r'MAC Address:.*\(([^)]+)\)'
    true_address_pattern = r'MAC Address: ([^ ]+) \('

    encoding = detect_encoding(file_path)
    with open(file_path, 'r', encoding=encoding) as file:
        content = file.read()
        targets = re.findall(target_pattern, content)
        mac_addresses = re.findall(mac_address_pattern, content)
        true_addresses = re.findall(true_address_pattern, content)

    return targets, mac_addresses, true_addresses


def main():
    # 创建Tkinter根窗口
    root = tk.Tk()
    root.withdraw()  # 隐藏主窗口

    # 打开文件选择对话框
    file_paths = filedialog.askopenfilenames(title='选择Nmap扫描结果文件', filetypes=[('Text files', '*.txt')])

    if not file_paths:
        print('没有选择文件，程序退出。')
        return

    # 提取Nmap扫描目标和MAC地址信息
    nmap_targets = []
    for file_path in file_paths:
        targets, mac_addresses, true_addresses = extract_nmap_targets(file_path)
        for target, mac_address, true_addresses in zip(targets, mac_addresses, true_addresses):
            nmap_targets.append({'File': file_path, 'IP': target, '厂商': mac_address, 'MAC地址': true_addresses})

    # 创建DataFrame
    df = pd.DataFrame(nmap_targets)

    # 输出到Excel文件
    output_file = 'nmap_targets.xlsx'
    df.to_excel(output_file, index=False)
    print(f'Nmap targets and MAC addresses have been extracted and saved to {output_file}')

if __name__ == '__main__':
    main()
